package com.it.chinamobileai.controller;

import com.it.chinamobileai.domain.vo.Result;
import com.it.chinamobileai.service.IChatHistoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.JsonReader;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai/service")
public class PdfController {
    @Autowired
    private VectorStore vectorStore;
    @Value("classpath:1.json")
    private Resource resource;
    /**
     * 文件上传
     */
    public Result uploadPdf() {
            this.writeToVectorStore(resource);
            return Result.ok();
    }
    private void writeToVectorStore(Resource resource) {
        JsonReader jsonReader = new JsonReader(resource);
        List<Document> documents = jsonReader.get();
        vectorStore.add(documents);
    }
    @Autowired
    private IChatHistoryService chatHistoryService;
    @Autowired
    private ChatClient pdfChatClient;
    @RequestMapping(produces = "text/html;charset=UTF-8")
    public Flux<String> chat(String prompt, String chatId) {
        chatHistoryService.saveChatHistory("service",chatId);
        this.uploadPdf();
        return pdfChatClient
                .prompt(prompt)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();
    }
}
